package gov.cn.user.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import gov.cn.user.entity.UserInfo;
import gov.cn.user.exception.UserException;
import gov.cn.user.service.UserService;
import gov.cn.user.vo.AjaxResult;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.Serializable;

@RestController
@RequestMapping("/user")
public class UserController {
    @Resource
    private UserService userService;

    @Resource
    protected HttpServletRequest request;

    @GetMapping("/list/{pageNum}/{pageSize}")
    public AjaxResult list(@PathVariable int pageNum, @PathVariable int pageSize, UserInfo userInfo) {
        //List<UserInfo> list = userService.list();
        //String userName = request.getParameter("userName");
        IPage page = userService.findByPage(pageNum, pageSize, userInfo);
        return AjaxResult.ok(page);
    }

    @GetMapping("/checkName")
    public AjaxResult list(UserInfo userInfo) {
        if (userService.checkName(userInfo)) {
            return AjaxResult.ok();
        }
        return AjaxResult.fail("重复");
    }

    @PostMapping("/add")
    public AjaxResult add(@RequestBody UserInfo user) {
        try {
            userService.add(user);
        } catch (UserException e) {
            return AjaxResult.fail(e.getMessage());
        }
        return AjaxResult.ok();
    }

    @GetMapping("/{id}")
    public AjaxResult getById(@PathVariable Serializable id) {
        return AjaxResult.ok(userService.getById(id));
    }

    @PutMapping("/edit")
    public AjaxResult edit(@RequestBody UserInfo user) {
        try {
            userService.updById(user);
        } catch (UserException e) {
            return AjaxResult.fail(e.getMessage());
        }
        return AjaxResult.ok();
    }

    @PutMapping("/nab/{id}")
    public AjaxResult nab(@PathVariable Serializable id) {
        try {
            userService.enableById(id);
        } catch (UserException e) {
            return AjaxResult.fail(e.getMessage());
        }
        return AjaxResult.ok();
    }

    @DeleteMapping("/{userId}")
    public AjaxResult removeById(@PathVariable Serializable userId) {
        userService.removeById(userId);
        return AjaxResult.ok();
    }


}
